<?php
/**
 * Created by PhpStorm.
 * User: lzy
 * Date: 2018/11/6
 * Time: 14:26
 */

namespace App\Base\Helpers\Lib;

use App\Base\Exceptions\WeixinException;

/**
 * 微信小程序
 * Class WxXiaoLibrary
 * @package App\Base\Helpers\Lib
 */
class WxXiaoLibrary
{
    private $appID;   //小程序ID
    private $appSecret;//小程序SessionKey

    public function __construct($appID, $appSecret)
    {
        $this->appID = $appID;
        $this->appSecret = $appSecret;
    }
    //进行解密

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData($encryptedData, $iv, $code, &$data)
    {
        //获取sessionkey
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $this->appID . "&secret=" . $this->appSecret . "&js_code=" . $code . "&grant_type=authorization_code";
        $res = json_decode($this->httpGet($url), true);//这边就可以取得openId
        if (!empty($res['errcode'])) {
            //不为空就报错了。。。微信报错
            throw new WeixinException(WeixinException::ERROR_XIAO_SESSION_KEY, ['msg' => $res['errmsg'] . "-" . $res['errcode']]);
        }
        $sessionKey = $res['session_key'];//取出json里对应的值
        if (strlen($sessionKey) != 24) {
            throw new WeixinException(WeixinException::ERROR_XIAO_AESKEY_ILLEGAL);
        }
        $aesKey = base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            throw new WeixinException(WeixinException::ERROR_XIAO_AES_ILLEGAL);
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            throw new WeixinException(WeixinException::ERROR_XIAO_BUFFER_ILLEGAL);
        }
        if ($dataObj->watermark->appid != $this->appID) {
            throw new WeixinException(WeixinException::ERROR_XIAO_BUFFER_ILLEGAL);
        }
        $data = $result;
        return $data;
    }

    /**
     * 获取小程序二维码
     * @param $access_token  访问token
     */
    public function createWXAQRCode($access_token){
            return $this->getAccessToken();
    }

    public function getAccessToken(){

        $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appID.'&secret='.$this->appSecret;

        $res=$this->httpGet($url);
        print_r($res);
        exit;
    }

    public function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    public function getSendResultInfo($code){
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $this->appID . "&secret=" . $this->appSecret . "&js_code=" . $code . "&grant_type=authorization_code";
        $res = json_decode($this->httpGet($url), true);//这边就可以取得openId
        if (!empty($res['errcode'])) {
            //不为空就报错了。。。微信报错
            throw new WeixinException(WeixinException::ERROR_XIAO_SESSION_KEY, ['msg' => $res['errmsg'] . "-" . $res['errcode']]);
        }
    }

}